package cn.baker.rabbitmq.listener;

import cn.baker.rabbitmq.service.TransMessageService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * 死信队列监听
 * @author yuanyu
 */
@Slf4j
@Component("dlxListener")
@ConditionalOnProperty("trans.rabbitMq.dlxEnabled")
public class DlxListener implements ChannelAwareMessageListener {

    @Autowired
    private TransMessageService transMessageService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String messageBody = new String(message.getBody());
        MessageProperties messageProperties = message.getMessageProperties();
        log.error("@mqLog 收到死信队列消息, message:[{}], tag:[{}]", messageBody, messageProperties.getDeliveryTag());
        // 发邮件、打电话、发短信
        //入库
        transMessageService.messageDead(
                messageProperties.getMessageId(),
                messageProperties.getReceivedExchange(),
                messageProperties.getReceivedRoutingKey(),
                messageProperties.getConsumerQueue(),
                messageBody
        );
        // 单条确认
        channel.basicAck(messageProperties.getDeliveryTag(), false);
    }

}
